<?php
use think\Cache;
use think\Request;
/*写文件*/
function content_log($pay_type,$url,$ip,$params,$content){
    db('cms_log')->insert(['ip'=>$ip, 'url'=>$url,'params'=>json_encode($params,JSON_UNESCAPED_UNICODE),'content'=>json_encode($content,JSON_UNESCAPED_UNICODE)]);
//     $date_path = RUNTIME_PATH.'ContentLog/'.date('Ym');
//     if(!file_exists($date_path)){
//         mkdir($date_path,0777,true);
//     }
//     $filename =$date_path.'/'.date('d').$pay_type.'.txt';
//     $Ts=fopen($filename,"a+");
//     fputs($Ts,"\r\n"."执行日期：".date('Y-m-d H:i:s',time())."\r\n"."执行url：".$url."\r\n"."ip:".$ip."\r\n"."参数:".json_encode($params,JSON_UNESCAPED_UNICODE). "\r\n" . "返回内容: ". "\r\n" .json_encode($content,JSON_UNESCAPED_UNICODE)."\n");
//     fclose($Ts);
}

/**
 * @param $m 模型，引用传递
 * @param $where 查询条件
 * @param int $pagesize 每页查询条数
 * @return \Think\Page
 */
function getpage($count,$pagesize,$parameter=array())
{

    $Page = new Think\Page($count, $pagesize);
    foreach($parameter as $key =>$value){
        $Page->parameter[$key]   =  $value;
    }

    return $Page->show();
}

/**
 * 把返回的数据集转换成Tree
 * @access public
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}


/*微信回调获取用户信息
@paramer  $redirect_url   回调网址
@paramer  $scope          授权方式
应用授权作用域，snsapi_base ，snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且，即使在未关注的情况下，只要用户授权，也能获取其信息）
@paramer  $state          用户自己定义的参数
return code
回调 返回code 或 $state用户定义的参数
*/
function wei_get_acquire_code($appId,$redirect_uri,$scope='snsapi_userinfo',$state='ABCD'){
            $redirect_uri=urlencode($redirect_uri);
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId.'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state='.$state.'&connect_redirect=1#wechat_redirect';
            // p($url);die;
            header("Location:".$url);
}

function wei_get_info($appId,$appSecret,$code){
    //根据code获得Access Token
    $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$appSecret.'&code='.$code.'&grant_type=authorization_code';
    $access_token_json =https_request($access_token_url);
    $access_token_array = json_decode($access_token_json,true);
    $openid = $access_token_array['openid'];
    $access_token = $access_token_array['access_token'];
    $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
    $output = httpGet($url);
    $info = json_decode($output,true);
    return $info;
}


function wei_get_openid($appId,$appSecret,$code){
    //根据code获得openid
    $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$appSecret.'&code='.$code.'&grant_type=authorization_code';
    $access_token_json =https_request($access_token_url);
    $access_token_array = json_decode($access_token_json,true);
    $openid = $access_token_array['openid'];
    return $openid;
}

function WechatInfo($openid){
        $accessToken = getAccessToken(C('APP_ID'),C('APP_SECRET'));
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openid&lang=zh_CN";
        $res = json_decode(httpGet($url),true);
        return $res;
}

  function https_request($url){
        $curl =curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        $data = curl_exec($curl);
        if(curl_errno($curl)){
            return 'ERROR '.curl_error($curl);
        }
        curl_close($curl);
        return $data;
}

   function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
}

function post($url, $post_data, $timeout = 3)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    if ($post_data != '') {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //声明进行json传输
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($post_data)));
    //设置超时的单位为秒
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $file_contents = curl_exec($ch);
    $CurlErrno = curl_errno($ch);
    $CurlError = curl_error($ch);
    curl_close($ch);
    if ($CurlErrno > 0) {
        return "服务器错误:($CurlErrno):$CurlError\n";
    } else {
        return $file_contents;
    }
}


//分享
function getSignPackage(){
        // 注意 URL 一定要动态获取，不能 hardcode.
        // $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        // $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url=Request::instance()->post('url');
        $appId = config('APPID');
        $jsapiticket = getJsApiTicket();
        $timestamp = time();
        $nonceStr = createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string,
            "jsApiList" => array('checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','hideMenuItems','showMenuItems','chooseWXPay','openAddress')
        );
        return $signPackage;
    }
//生成access_token
function getAccessToken($appId,$appSecret) {
    if(Cache::get('access_token')){
         $access_token=Cache::get('access_token');
     }else{

         $access_token_url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;

         $res = json_decode(httpGet($access_token_url),true);

         Cache::set('access_token',$res['access_token'],7000);
         $access_token=Cache::get('access_token');
     }
    
     return $access_token;
 }
 
function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
function getJsApiTicket() {
        if(Cache::get('ticket')){
            $ticket=Cache::get('ticket');
        }else{
            $accessToken = getAccessToken(config('APPID'),config('APPSECRET'));

            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";

            $res = json_decode(httpGet($url),true);
            // dump($res);
            Cache::set('ticket',$res['ticket'],7000);
            $ticket=Cache::get('ticket');
        }

        return $ticket;
 }

//获取签名
 function get_sign($data=array()){
    $str='';
    foreach($data as $k=>$v){
        if($v===null||$v==='')
         unset( $data[$k] );
    }
    ksort($data);
    foreach($data as $key =>$value){
        $str.=$key.'='.$value.'&';
    }
    $sign=$str.C('ACCESS');
    $sign=strtolower(MD5($sign));
    return $sign;
 }

/**
 * 显示错误，并中断程序执行
 * @param string $des 错误描述
 */
function show_error($msg,$code=300) {
    $arr=array(
        'status'    =>      'error',
        'msg'       =>      $msg,
        'code'      =>      $code
    );
    return $arr;
}

/**
 * @author jerry xiao
 * @param array $data 返回json
 */
function show_success($msg,$code=200)
{
    $arr=array(
        'status'    =>      'ok',
        'msg'       =>      $msg,
        'code'      =>      $code
    );
    return $arr;
}

function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

function is_Weixin()
{
    if( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false ) {
        $url = 'http://' . C('WAWADOMAIN') . '/index.php/Shop/Passport/login';
        wei_get_acquire_code(C('APP_ID'), $url, 'snsapi_base');
    }
}
/**
 * 功能：生成二维码
 * @param string $qr_data   手机扫描后要跳转的网址
 * @param string $qr_level  默认纠错比例 分为L、M、Q、H四个等级，H代表最高纠错能力
 * @param string $qr_size   二维码图大小，1－10可选，数字越大图片尺寸越大
 * @param string $save_path 图片存储路径
 * @param string $save_prefix 图片名称前缀
 */
function createQRcode($save_path,$qr_data='PHP QR Code :)',$qr_level='L',$qr_size=4,$save_prefix='qrcode',$logo="",$is_logo=fasle){
    if(!isset($save_path)) return '';
    //设置生成png图片的路径
    $PNG_TEMP_DIR = & $save_path;
    //导入二维码核心程序
    vendor("PHPQrcode.phpqrcode");  //注意这里的大小写哦，不然会出现找不到类，PHPQRcode是文件夹名字，class#phpqrcode就代表class.phpqrcode.php文件名
    //检测并创建生成文件夹
    $qrcode =new \QRcode();
    if (!file_exists($PNG_TEMP_DIR)){
        mkdir($PNG_TEMP_DIR);
    }
    $filename = $PNG_TEMP_DIR.'test.png';
    $errorCorrectionLevel = 'L';
    if (isset($qr_level) && in_array($qr_level, array('L','M','Q','H'))){
        $errorCorrectionLevel = & $qr_level;
    }
    $matrixPointSize = 4;
    if (isset($qr_size)){
        $matrixPointSize = & min(max((int)$qr_size, 1), 10);
    }
    if (isset($qr_data)) {
        if (trim($qr_data) == ''){
            die('data cannot be empty!');
        }
        //生成文件名 文件路径+图片名字前缀+md5(名称)+.png
        $filename = $PNG_TEMP_DIR.$save_prefix.md5($qr_data.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
        //开始生成
        $qrcode->png($qr_data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
            if ($is_logo === true) {
                  $filename = imagecreatefromstring(file_get_contents($filename));
                  $logo = imagecreatefromstring(file_get_contents($PNG_TEMP_DIR.$logo));
                  $QR_width = imagesx($filename);//二维码图片宽度
                  $QR_height = imagesy($filename);//二维码图片高度
                  $logo_width = imagesx($logo);//logo图片宽度
                  $logo_height = imagesy($logo);//logo图片高度
                  $logo_qr_width = $QR_width / 4;
                  $scale = $logo_width/$logo_qr_width;
                  $logo_qr_height = $logo_height/$scale;
                  $from_width = ($QR_width - $logo_qr_width) / 2;
                  //重新组合图片并调整大小
                  imagecopyresampled($filename, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                  $logo_qr_height, $logo_width, $logo_height);
                  $image_logo=$PNG_TEMP_DIR.$save_prefix.md5($qr_data.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
                  imagepng($filename,$image_logo);
                  if(file_exists($PNG_TEMP_DIR.basename($image_logo))){
                        return basename($image_logo);
                    }else{
                        return FALSE;
                    }
            }

    } else {
        //默认生成
        $qrcode->png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    }

    if(file_exists($PNG_TEMP_DIR.basename($filename))){

        return basename($filename);
    }else{
        return FALSE;
    }
}

//将编辑器上传的html实体化
function get_content_transferred($content){
    $search = array ("'<script[^>]*?>.*?</script>'si", // 去掉 javascript
         "'<[\/\!]*?[^<>]*?>'si",      // 去掉 HTML 标记
         "'([\r\n])[\s]+'",         // 去掉空白字符
         "'&(quot|#34);'i",         // 替换 HTML 实体
         "'&(amp|#38);'i",
         "'&(lt|#60);'i",
         "'&(gt|#62);'i",
         "'&(nbsp|#160);'i",
         "'&(iexcl|#161);'i",
         "'&(cent|#162);'i",
         "'&(pound|#163);'i",
         "'&(copy|#169);'i",
         "'&#(\d+);'e");          // 作为 PHP 代码运行
        $replace = array ("",
         "",
         "\\1",
         "\"",
         "&",
         "<",
         ">",
         " ",
         chr(161),
         chr(162),
         chr(163),
         chr(169),
         "chr(\\1)");
    return  preg_replace($search,$replace,$content);
}
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=false){
 if(function_exists("mb_substr")){
 if($suffix)
 return mb_substr($str, $start, $length, $charset)."...";
 else
 return mb_substr($str, $start, $length, $charset);
 }elseif(function_exists('iconv_substr')) {
 if($suffix)
 return iconv_substr($str,$start,$length,$charset)."...";
 else
 return iconv_substr($str,$start,$length,$charset);
 }
 $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
 $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
 $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
 $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
 preg_match_all($re[$charset], $str, $match);
 $slice = join("",array_slice($match[0], $start, $length));
 if($suffix) return $slice."…";
 return $slice;
}

function p($param){
    echo '<pre>';
    print_r($param);
    echo '</pre>';
}

function randshare() {
 mt_srand((double) microtime() * 1000000);
 return str_pad(mt_rand(1, 999999), 6, STR_PAD_LEFT);
}
function randusercode() {
 mt_srand((double) microtime() * 10000000);
 return str_pad(mt_rand(1, 999999), 6, STR_PAD_LEFT);
}

//二维数组去重
function er_array_unique($arr){
    $newarr = array();
    if(is_array($arr)){
        foreach($arr as $v){
            if(!in_array($v,$newarr,true)){
                $newarr[] = $v;
            }
        }
    }else{
        return false;
    }
    return $newarr;
}

//删除为空的数组
function unset_empty_array($data){
    foreach($data as $k=>$v){
        if($v===null||$v===''){
            unset($data[$k]);
        }
    }
    ksort($data);
    return $data;
}



